import React, { useEffect, useState } from "react";
import { Button, Container } from "react-bootstrap";
import {createGraphiQLFetcher} from "@graphiql/toolkit";
import {GraphiQL} from 'graphiql'
import "graphiql/graphiql.min.css"
import "./graphiql.css"

const GraphQLPlayground:React.FC = (props)=> {

    const [status,setStatus] = useState<string>();
    const queryStr = `{
        getAllOrders{
            id
            userId
            firstName
            lastName
            address
            city
            country
            zipCode
            totalAmount
            items
            createDate
        }
    }`
    const start = async ()=>{
        setStatus("Start...");
        console.log('graphql endpoint:',process.env.REACT_APP_GRAPHQL_ENDPOINT)
       const resp = await fetch(`${process.env.REACT_APP_GRAPHQL_ENDPOINT}/graphqlapi`,{
            method:"POST",
            headers:{"Content-Type":"application/json"},
            body: JSON.stringify({query:queryStr})
        });
        const json = await resp.json()
       console.log("get result: ",json);
       const str = JSON.stringify(json.data.getAllOrders);
       setStatus(str as string)
    }


    const fetcher = createGraphiQLFetcher({url:`${process.env.REACT_APP_GRAPHQL_ENDPOINT}/graphqlapi`})

    return (<Container style={{flex:1,padding:5}} fluid>
        <div>Example: <code>{queryStr}</code></div>
        <div>
            <Button onClick={start}>Test</Button>
        </div>
        <div>
            {status}
        </div>
        <GraphiQL className="custom-container" fetcher={fetcher}></GraphiQL>
    </Container>)
}

export default GraphQLPlayground;